/*
 * Copyright (C) 2011 Reeny
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.tobidodo.spritmonclient.data;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import de.tobidodo.spritmonclient.util.LogHelper;

/**
 * A utility class to manage the persisting processes
 * of fueling data.
 * @author Reeny
 */
public class FuelDataPersister {

	
	public static int insert(Activity ownerActivity, final String fuelingDate, final FuelDataDTO data) {

		ContentValues values = new ContentValues();
		values.put(FuelDataProvider.FUEL_DATE, fuelingDate);
		values.put(FuelDataProvider.TOT_DIST, data.getTotalDistanceValue());
		values.put(FuelDataProvider.LAST_DIST, data.getPeriodDistanceValue());
		values.put(FuelDataProvider.FUEL_IN, data.getFuelAmountValue());
		values.put(FuelDataProvider.FUEL_COST, data.getFuelPriceValue());
		values.put(FuelDataProvider.UPDATE_TIME, DateFormatUtil.currentDateToString());
		values.put(FuelDataProvider.CREATION_TIME, DateFormatUtil.currentDateToString());
		
		Uri insertedItem = ownerActivity.getContentResolver().insert(FuelDataProvider.CONTENT_ITEM_URI, values);
		
		if (insertedItem == null){
			throw new NullPointerException("Got 'null' as insertion result. Item may not be inserted.");
		}
		
		String insertedId = insertedItem.getPathSegments().get(FuelDataProvider.ITEM_ID_PATH_POSITION);
		if (insertedId == null){
			throw new NullPointerException("Got 'null' as ID from insertion result. Item may not be inserted.");
		}
		
		return Integer.valueOf(insertedId);
		
		/*
		if (this.db == null){
			startFuelDataPersister();
		}
		
		this.preparedInsertStmnt.clearBindings();

		this.preparedInsertStmnt.bindString(1, fuelingDate);
		this.preparedInsertStmnt.bindString(2, data.getTotalDistanceValue());
		this.preparedInsertStmnt.bindString(3, data.getPeriodDistanceValue());
		this.preparedInsertStmnt.bindString(4, data.getFuelAmountValue());
		this.preparedInsertStmnt.bindString(5, data.getFuelPriceValue());
		this.preparedInsertStmnt.bindString(6, DateFormatUtil.currentDateToString());
		this.preparedInsertStmnt.bindString(7, DateFormatUtil.currentDateToString());

		long rowid = this.preparedInsertStmnt.executeInsert();
		//this.preparedInsertStmnt.close();
		data.setCurrentDbId(rowid != -1 ? Long.valueOf(rowid) : null);
		return rowid;
		*/
	}
	

	public static int update(Activity ownerActivity, final String fuelingDate, final FuelDataDTO newdata) {

		ContentValues values = new ContentValues();
		values.put(FuelDataProvider.FUEL_DATE, fuelingDate);
		values.put(FuelDataProvider.TOT_DIST, newdata.getTotalDistanceValue());
		values.put(FuelDataProvider.LAST_DIST, newdata.getPeriodDistanceValue());
		values.put(FuelDataProvider.FUEL_IN, newdata.getFuelAmountValue());
		values.put(FuelDataProvider.FUEL_COST, newdata.getFuelPriceValue());
		values.put(FuelDataProvider.UPDATE_TIME, DateFormatUtil.currentDateToString());

		String condition = FuelDataProvider._ID + " = " + newdata.getCurrentDbId();
		
		ownerActivity.getContentResolver().update(FuelDataProvider.CONTENT_ITEM_URI, values, condition, null);
		
		return newdata.getCurrentDbId();		
		
		/*
		if (this.db == null){
			startFuelDataPersister();
		}
		
		ContentValues values = new ContentValues();
		values.put(COLNAME_FUEL_DATE, fuelingDate);
		values.put(COLNAME_TOT_DIST, newdata.getTotalDistanceValue());
		values.put(COLNAME_LAST_DIST, newdata.getPeriodDistanceValue());
		values.put(COLNAME_FUEL_IN, newdata.getFuelAmountValue());
		values.put(COLNAME_FUEL_COST, newdata.getFuelPriceValue());
		values.put(COLNAME_UPDATE_TIME, DateFormatUtil.currentDateToString());
		
		String condition = COLNAME_FUELID + " = " + newdata.getCurrentDbId();
		
		this.db.update(TBLNAME_FUELDATA, values, condition, null);
		
		return newdata.getCurrentDbId();
		*/

	}
	
	public static int updateTransmitDate(Activity ownerActivity, final int rowId){

		ContentValues values = new ContentValues(1);
		values.put(FuelDataProvider.TRANSMIT_TIME, DateFormatUtil.currentDateToString());
		
		ownerActivity.getContentResolver().update(FuelDataProvider.CONTENT_ITEM_URI, values, FuelDataProvider._ID+"="+rowId, null);

		return rowId;	
		
		/*
		if (this.db == null){
			startFuelDataPersister();
		}
		
		ContentValues values = new ContentValues(1);
		values.put(COLNAME_TRANSMIT_TIME, DateFormatUtil.currentDateToString());
		return db.updateWithOnConflict(TBLNAME_FUELDATA, values, COLNAME_FUELID+"="+rowId, null, SQLiteDatabase.CONFLICT_ROLLBACK);
		*/
	}


	public static int updateErrorId(Activity ownerActivity, final int rowId, final int errMsgId){

		
		ContentValues values = new ContentValues(1);
		values.put(FuelDataProvider.ERROR, errMsgId);
		
		ownerActivity.getContentResolver().update(FuelDataProvider.CONTENT_ITEM_URI, values, FuelDataProvider._ID+"="+rowId, null);
		
		return rowId;
		
		/*
		if (this.db == null){
			startFuelDataPersister();
		}
		
		ContentValues values = new ContentValues(1);
		values.put(COLNAME_ERROR, errMsgId);
		
		return db.updateWithOnConflict(TBLNAME_FUELDATA, values, COLNAME_FUELID+"="+rowId, null, SQLiteDatabase.CONFLICT_ROLLBACK);
		*/
	}

	
	public static void deleteAll(Activity ownerActivity){
		/*
		if (this.db == null){
			startFuelDataPersister();
		}
		this.db.delete(TBLNAME_FUELDATA, null, null);
		*/
		
		LogHelper.logInfo("Note: Deleting all fuel data entries!");
		
		ownerActivity.getContentResolver().delete(FuelDataProvider.CONTENT_LIST_URI, null, null);
	}

	public static FuelDataDTO getFuelEntry(Activity ownerActivity, final long dataid){
		if (dataid == -1){
			return null;
		}
		

		Uri fueldataItemUri = ContentUris.withAppendedId(FuelDataProvider.CONTENT_ITEM_URI, dataid);
		Cursor cursor = ownerActivity.managedQuery(fueldataItemUri, null, null, null, null);

		try{
			if (cursor.moveToFirst()) {
				FuelDataDTO dbEntry = cursorToFuelDataDTO(cursor);
				
				return dbEntry;
			}
		}
		finally{
			if (cursor != null && !cursor.isClosed()){
				cursor.close();
			}
		}
		
		return null;
		
		/*
		if (this.db == null){
			startFuelDataPersister();
		}
		
		String[] colnames = new String[]{COLNAME_FUELID, COLNAME_FUEL_DATE, COLNAME_TOT_DIST, COLNAME_LAST_DIST, COLNAME_FUEL_IN, COLNAME_FUEL_COST, COLNAME_UPDATE_TIME, COLNAME_TRANSMIT_TIME, COLNAME_ERROR};
		Cursor cursor = this.db.query(TBLNAME_FUELDATA, colnames, COLNAME_FUELID+" = "+dataid, null, null, null, null);
		
		try{
			if (cursor.moveToFirst()) {
				FuelDataDTO dbEntry = new FuelDataDTO();
				
				dbEntry.setCurrentDbId(cursor.getString(0));
				dbEntry.setTotalDistanceValue(cursor.getString(2));
				dbEntry.setPeriodDistanceValue(cursor.getString(3));
				dbEntry.setFuelAmountValue(cursor.getString(4));
				dbEntry.setFuelPriceValue(cursor.getString(5));
				dbEntry.setLastErrorId(cursor.getString(8));
				dbEntry.setUpdatedTime(cursor.getString(6));
				dbEntry.setTransmittedTime(cursor.getString(7));
				
				return dbEntry;
			}
		}
		finally{
			if (cursor != null && !cursor.isClosed()){
				cursor.close();
			}
		}
		return null;
		*/
	}

	
	public static FuelDataDTO getLastFuelEntry(Activity ownerActivity){

		Cursor cursor = ownerActivity.managedQuery(FuelDataProvider.CONTENT_LIST_URI, null, FuelDataProvider.TRANSMIT_TIME+" is null", null, FuelDataProvider.UPDATE_TIME+" desc");

		try{
			if (cursor.moveToFirst()) {
				FuelDataDTO dbEntry = cursorToFuelDataDTO(cursor);
				
				return dbEntry;
			}
		}
		finally{
			if (cursor != null && !cursor.isClosed()){
				cursor.close();
			}
		}
		
		return null;
		
		/*
		if (this.db == null){
			startFuelDataPersister();
		}
		

		String[] colnames = new String[]{COLNAME_FUELID, COLNAME_FUEL_DATE, COLNAME_TOT_DIST, COLNAME_LAST_DIST, COLNAME_FUEL_IN, COLNAME_FUEL_COST, COLNAME_UPDATE_TIME, COLNAME_TRANSMIT_TIME, COLNAME_ERROR};
		Cursor cursor = this.db.query(TBLNAME_FUELDATA, colnames, COLNAME_TRANSMIT_TIME+" is null", null, null, null, COLNAME_UPDATE_TIME+" desc");
		try{
			if (cursor.moveToFirst()) {
				FuelDataDTO dbEntry = new FuelDataDTO();
				
				dbEntry.setCurrentDbId(cursor.getString(0));
				dbEntry.setTotalDistanceValue(cursor.getString(2));
				dbEntry.setPeriodDistanceValue(cursor.getString(3));
				dbEntry.setFuelAmountValue(cursor.getString(4));
				dbEntry.setFuelPriceValue(cursor.getString(5));
				dbEntry.setLastErrorId(cursor.getString(8));
				dbEntry.setUpdatedTime(cursor.getString(6));
				dbEntry.setTransmittedTime(cursor.getString(7));
				
				return dbEntry;
			}
		}
		finally{
			if (cursor != null && !cursor.isClosed()){
				cursor.close();
			}
		}
		return null;
		*/
	}
	

	public static FuelDataDTO getPrevFuelEntry(Activity ownerActivity, final long rowId){
		if (rowId == -1){
			return null;
		}
		

		Cursor cursor = ownerActivity.managedQuery(FuelDataProvider.CONTENT_LIST_URI, null, FuelDataProvider.TRANSMIT_TIME+" is null", null, FuelDataProvider.UPDATE_TIME+" asc");

		try{
			while(cursor.moveToNext()) {
				if (cursor.getInt(cursor.getColumnIndex(FuelDataProvider._ID)) == rowId){
					if (!cursor.moveToPrevious()){
						LogHelper.logInfo("keine Eintrag vor dem angegeben Eintrag gefunden");
						return null;
					}
					
					FuelDataDTO dbEntry = cursorToFuelDataDTO(cursor);
					
					return dbEntry;
				}
			}
		}
		finally{
			if (cursor != null && !cursor.isClosed()){
				cursor.close();
			}
		}
		
		return null;
		
		/*
		if (this.db == null){
			startFuelDataPersister();
		}
		
		String[] colnames = new String[]{COLNAME_FUELID, COLNAME_FUEL_DATE, COLNAME_TOT_DIST, COLNAME_LAST_DIST, COLNAME_FUEL_IN, COLNAME_FUEL_COST, COLNAME_UPDATE_TIME, COLNAME_TRANSMIT_TIME, COLNAME_ERROR};
		Cursor cursor = this.db.query(TBLNAME_FUELDATA, colnames, COLNAME_TRANSMIT_TIME+" is null", null, null, null, COLNAME_UPDATE_TIME+" asc");
		
		try{
		while(cursor.moveToNext()) {
			
		
			// gesuchte ID gefunden?
			if (cursor.getInt(0) == rowId){
				if (!cursor.moveToPrevious()){
					LogHelper.logInfo("keine Eintrag vor dem angegeben Eintrag gefunden");
					return null;
				}
				
				FuelDataDTO dbEntry = new FuelDataDTO();
				
				dbEntry.setCurrentDbId(cursor.getString(0));
				dbEntry.setTotalDistanceValue(cursor.getString(2));
				dbEntry.setPeriodDistanceValue(cursor.getString(3));
				dbEntry.setFuelAmountValue(cursor.getString(4));
				dbEntry.setFuelPriceValue(cursor.getString(5));
				dbEntry.setLastErrorId(cursor.getString(8));
				dbEntry.setUpdatedTime(cursor.getString(6));
				dbEntry.setTransmittedTime(cursor.getString(7));
				
				return dbEntry;
			}
			
		}	
			
		}
		finally{
			if (cursor != null && !cursor.isClosed()){
				cursor.close();
			}
		}

		
		return null;
		*/
	}
	
	public static FuelDataDTO getNextFuelEntry(Activity ownerActivity, final long rowId){
		if (rowId == -1){
			return null;
		}
		

		Cursor cursor = ownerActivity.managedQuery(FuelDataProvider.CONTENT_LIST_URI, null, FuelDataProvider.TRANSMIT_TIME+" is null", null, FuelDataProvider.UPDATE_TIME+" asc");

		try{
			while(cursor.moveToNext()) {
				if (cursor.getInt(cursor.getColumnIndex(FuelDataProvider._ID)) == rowId){
					if (!cursor.moveToNext()){
						LogHelper.logInfo("keine Eintrag nach dem angegeben Eintrag gefunden");
						return null;
					}
					
					FuelDataDTO dbEntry = cursorToFuelDataDTO(cursor);
					
					return dbEntry;
				}
			}
		}
		finally{
			if (cursor != null && !cursor.isClosed()){
				cursor.close();
			}
		}
		
		return null;
		/*
		if (this.db == null){
			startFuelDataPersister();
		}
		
		String[] colnames = new String[]{COLNAME_FUELID, COLNAME_FUEL_DATE, COLNAME_TOT_DIST, COLNAME_LAST_DIST, COLNAME_FUEL_IN, COLNAME_FUEL_COST, COLNAME_UPDATE_TIME, COLNAME_TRANSMIT_TIME, COLNAME_ERROR};
		Cursor cursor = this.db.query(TBLNAME_FUELDATA, colnames, COLNAME_TRANSMIT_TIME+" is null", null, null, null, COLNAME_UPDATE_TIME+" asc");
		
		try{
		while(cursor.moveToNext()) {
			
		
			// gesuchte ID gefunden?
			if (cursor.getInt(0) == rowId){
				if (!cursor.moveToNext()){
					LogHelper.logInfo("keine Eintrag nach dem angegeben Eintrag gefunden");
					return null;
				}

				FuelDataDTO dbEntry = new FuelDataDTO();
				
				dbEntry.setCurrentDbId(cursor.getString(0));
				dbEntry.setTotalDistanceValue(cursor.getString(2));
				dbEntry.setPeriodDistanceValue(cursor.getString(3));
				dbEntry.setFuelAmountValue(cursor.getString(4));
				dbEntry.setFuelPriceValue(cursor.getString(5));
				dbEntry.setLastErrorId(cursor.getString(8));
				dbEntry.setUpdatedTime(cursor.getString(6));
				dbEntry.setTransmittedTime(cursor.getString(7));
				
				return dbEntry;
			}
			
		}	
			
		}
		finally{
			if (cursor != null && !cursor.isClosed()){
				cursor.close();
			}
		}
		
		return null;
		*/
	}
	


	private static FuelDataDTO cursorToFuelDataDTO(Cursor cursor) {
		FuelDataDTO dbEntry = new FuelDataDTO();
		
		dbEntry.setCurrentDbId(cursor.getString(cursor.getColumnIndex(FuelDataProvider._ID)));
		dbEntry.setTotalDistanceValue(cursor.getString(cursor.getColumnIndex(FuelDataProvider.TOT_DIST)));
		dbEntry.setPeriodDistanceValue(cursor.getString(cursor.getColumnIndex(FuelDataProvider.LAST_DIST)));
		dbEntry.setFuelAmountValue(cursor.getString(cursor.getColumnIndex(FuelDataProvider.FUEL_IN)));
		dbEntry.setFuelPriceValue(cursor.getString(cursor.getColumnIndex(FuelDataProvider.FUEL_COST)));
		dbEntry.setLastErrorId(cursor.getString(cursor.getColumnIndex(FuelDataProvider.ERROR)));
		dbEntry.setUpdatedTime(cursor.getString(cursor.getColumnIndex(FuelDataProvider.UPDATE_TIME)));
		dbEntry.setTransmittedTime(cursor.getString(cursor.getColumnIndex(FuelDataProvider.TRANSMIT_TIME)));
		return dbEntry;
	}
}
